package ${pPackage}.common.handler;

import ${pPackage}.common.entity.Result;
import ${pPackage}.common.entity.ResultCode;
import ${pPackage}.common.exception.CommonException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 自定义的公共异常处理器
 * 声明异常处理器
 * 对异常统一处理
 *
 * @author hl
 */
@ControllerAdvice
public class GlobalExceptionHandler {

  static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

  //shiro 异常
  @ExceptionHandler(value = AuthorizationException.class)
  @ResponseBody
  public Result error(HttpServletRequest request, HttpServletResponse response, AuthorizationException e) {
    return new Result(ResultCode.E_110010);
  }

  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public Result error(HttpServletRequest request, HttpServletResponse response, Exception e) {
    e.printStackTrace();
    if (e.getClass() == CommonException.class) {
      // 自定义的公共异常处理器
      CommonException ce = (CommonException) e;
      Result result = new Result(ce.getResultCode());
      return result;
    } else if (e.getClass() == HttpMessageNotReadableException.class) {
      // 参数格式不正确异常处理器
      return new Result(ResultCode.E_100101);
    } else if (e.getClass() == MethodArgumentNotValidException.class) {
      // 参数校验异常处理器
      MethodArgumentNotValidException ce = (MethodArgumentNotValidException) e;
      BindingResult bindingResult = ce.getBindingResult();
      List<ObjectError> allErrors = bindingResult.getAllErrors();
//            ArrayList<Map> list = new ArrayList<>();
//            for (ObjectError allError : allErrors) {
//                HashMap<Object, Object> map = new HashMap<>();
//                String field = ((FieldError) allError).getField();
//                String message = ((FieldError) allError).getDefaultMessage();
//                map.put("field", field);
//                map.put("message", message);
//                list.add(map);
//            }
      String message = allErrors.get(0).getDefaultMessage();
      return new Result(20005, message, false);
    } else if (e.getClass() == DuplicateKeyException.class) {
      // 索引冲突
      return new Result(20005, "索引冲突=>" + e.getCause().getMessage(), false);
    } else {
      return new Result(ResultCode.UNKNOWN);
    }
  }
}


